# encoding: UTF-8

require 'digest/sha1'
require "time"
require "net/http"
require "net/https"
require "uri"
require "json"

@uri_auth = URI.parse("https://192.168.198.128/service/verificar_autenticacao")
@uri = URI.parse("https://192.168.198.128/service/atualizar_exame")
@usuario = "paciente"
@senha = "123456"

inicio = Time.now.strftime("%Y-%m-%d %H:%M:%S")

header = {'Content-Type' =>'application/json'}

auth_token = Digest::SHA1.hexdigest("#{@senha}:_Y%l9#Bz5k:#{@usuario}")
param = {:authenticity_token => auth_token}

request = Net::HTTP::Post.new(@uri_auth.path, header)
request.basic_auth(@usuario, @senha)
request.body = param.to_json
https = Net::HTTP.new(@uri.host, @uri.port)
https.use_ssl = true
https.verify_mode = OpenSSL::SSL::VERIFY_NONE
https.ca_file = "/etc/ssl/certs/server.crt"
response = https.start {|http| http.request(request) }

puts "===========================[Autenticacao]==========================="
puts "Authenticity Token #{auth_token}"
puts "Response #{response.code} #{response.message}: #{response.body}"
puts

intervalo = 100

if response.code == "200"
  (0..10).each do |envio|
    dados_ecg = {}
    dados_acel = {}
    (0..10).each do |indice|
      dados_ecg[indice.to_s] = {:derivacao_1 => rand(2000),
                                :derivacao_2 => rand(2000),
                                :derivacao_3 => rand(2000),
                                :intervalo => (intervalo - (indice * 10))}
      dados_acel[indice.to_s] = {:eixo_x => rand(2000) + 100,
                                 :eixo_y => rand(2000) + 100,
                                 :eixo_z => rand(2000) + 100,
                                 :intervalo => (intervalo - (indice * 10))}
    end
    auth_token = Digest::SHA1.hexdigest("#{@senha}:_Y%l9#Bz5k:#{@usuario}")
    param = {:authenticity_token => auth_token,
             :inicio => inicio,
             :dados_ecg => dados_ecg,
             :dados_acel => dados_acel}

    header = {'Content-Type' =>'application/json'}

    request = Net::HTTP::Post.new(@uri.path, header)
    request.basic_auth(@usuario, @senha)
    request.body = param.to_json
    https = Net::HTTP.new(@uri.host, @uri.port)
    https.use_ssl = true
    https.verify_mode = OpenSSL::SSL::VERIFY_NONE
    https.ca_file = "/etc/ssl/certs/server.crt"
    response = https.start {|http| http.request(request) }

    puts "===========================[ #{envio} ]==========================="
    puts "[Header]"
    request.each_header do |header_name, header_value|
      puts "#{header_name} : #{header_value}"
    end
    puts "[Body]"
    puts "#{request.body}"
    puts
    puts "[Authenticity Token]"
    puts "#{auth_token}"
    puts
    puts "[Response]"
    puts "#{response.code} #{response.message}: #{response.body}"

    #sleep 1 # Tempo em segundos entre envios
    
    intervalo += 110
  end
end
